import {ref} from 'vue'
const actionEnum = {
    ADD : "新增",
    EDIT :  "编辑",
    QUERY :  "查询",
    NONE : ''
}
function useSForm(formDefaultValue={},
                 api={}){

    const formActionType = ref(undefined)
    const formRef = ref(undefined)
    const formValue = ref({...formDefaultValue})

    const {editApi,addApi,queryApi,getInfoById} = api
    /**
     * 新增
     */
    const onAdd = (flag) => {
        formActionType.value = flag ? actionEnum.NONE : actionEnum.ADD
        formValue.value = {...formDefaultValue}
    }

    /**
     * 编辑
     * @param row
     * @param id
     */
    const onEdit = (row,id) => {
        formActionType.value = actionEnum.EDIT
        if(getInfoById && id){
            getInfoById(id).then((res) => {
                formValue.value = {...res.data}
            })
        }else {
            formValue.value = {...row}
        }
    }

    /**
     * 查询
     */
    const onQuery = () => {
        return new Promise((resolve, reject) => {
            formActionType.value = actionEnum.QUERY
            resolve(formValue.value)
        })
    }


    /**
     * 保存
     * 返回 Promise，解决函数执行完后需要续写逻辑的需求
     */
    const onSubmit = () => {
        return new Promise((resolve, reject) => {
            formRef.value?.validate(err => {
                if (!err) {
                    if (formActionType.value === actionEnum.ADD && addApi) {
                        addApi(formValue.value).then((res) => {
                            naive.message.success(res.msg)
                            resolve(res)
                        })
                    }else if (formActionType.value === actionEnum.EDIT && editApi) {
                        editApi(formValue.value).then((res) => {
                            naive.message.success(res.msg)
                            resolve(res)
                        })
                    }else {
                        resolve()
                    }
                } else {

                }
            })
        })
    }

    /**
     * 重置
     * 返回 Promise，解决函数执行完后需要续写逻辑的需求
     */
    const onReset = () => {
        return new Promise((resolve, reject) => {
            const formDefaultKeys = Object.keys(formDefaultValue)
            const formKeys = Object.keys(formValue.value)
            formKeys.map(key => {
                if (formDefaultKeys.includes(key)) {
                    formValue.value[key] = formDefaultValue[key]
                } else {
                    formValue.value[key] = null
                }
            })
            resolve(formValue.value)
        })
    }

    const loadRules= (rule) => {
        formRef.value?.loadRules(rule)
    }
    return {
        onAdd,
        onEdit,
        onQuery,
        onSubmit,
        onReset,
        formValue,
        formRef,
        loadRules,
        formActionType
    }
}
export default useSForm;